#encoding=utf-8
'''
Created on 2018-8-9

@author: cooler
'''
import sys,os
reload(sys)
sys.setdefaultencoding('utf8')
sys.path.append("./")

from catgateio.GateIO import GateIO
from service.models import *
from utils.Monitor import Monitor

from key import apiKey,secretKey

import logging.handlers
import logging,time

logger = logging.getLogger()   
logfile = logging.handlers.TimedRotatingFileHandler(os.path.join(os.getcwd(), "logs/trade"), 'D', 1, 0)
# 设置后缀名称，跟strftime的格式一样
logfile.suffix = "%Y%m%d.log"
logger.addHandler(logfile) 
#set formater  
#formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s") 
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(process)d - Line:%(lineno)d - %(message)s")  
logfile.setFormatter(formatter)   
logger.setLevel(logging.INFO) 

    


def init_user_info():
    user_info = User_info()
    user_info['name'] = "cat"
    user_info['phone'] = "18515222233"
    user_info['email'] = "zhoupeng@ofo.com"
    user_info['apikey'] = "nokey"
    user_info['secretKey'] = "nosecretKey"
    user_info['id_rsa'] = "id_rsa"
    user_info['id_rsa_pub'] = "id_rsa_pub"
    user_info.save()

def init_wallet(user_info,gateio_info,name_cn,amount):
    wallet = Wallet()
    wallet['user_info'] = user_info
    wallet['gateio_info'] = gateio_info
    wallet['name_cn'] = name_cn
    wallet['amount'] = float(amount)
    wallet.save()
    return wallet

def buy(user_info,gateio_info,strategy_info,currency_pair,ticker,in_wallet,out_wallet,filledrate):
    logger.info( "交易前【支出账户（{0}）:{1},收入账户（{2}）:{3}】".format(out_cash,out_wallet['amount'],in_cash,in_wallet['amount']))
    buyrate = wallet_change_buy(user_info,gateio_info,strategy_info,currency_pair,ticker,in_wallet,out_wallet,filledrate)
    logger.info( "交易后【支出账户（{0}）:{1},收入账户（{2}）:{3}】".format(out_cash,out_wallet['amount'],in_cash,in_wallet['amount']))
    return buyrate

def sell(user_info,gateio_info,strategy_info,currency_pair,ticker,filledrate):
    logger.info( "交易前【支出账户（{0}）:{1},收入账户（{2}）:{3}】".format(out_cash,out_wallet['amount'],in_cash,in_wallet['amount']))
    sellrate = wallet_change_sell(user_info,gateio_info,strategy_info,currency_pair,ticker,in_wallet,out_wallet,filledrate)
    logger.info( "交易后【支出账户（{0}）:{1},收入账户（{2}）:{3}】".format(out_cash,out_wallet['amount'],in_cash,in_wallet['amount']))
    return sellrate

def wallet_change_buy(user_info,gateio_info,strategy_info,currency_pair,ticker,in_wallet,out_wallet,filledrate=0):
    rate = float(ticker['last'])#汇率
    b_money = filledrate#交易数量
    market_info = Market_info.objects(currency_pair=currency_pair).first()#交易手续费
    fee = float(market_info['fee'])/100
    b_num = (b_money-b_money*fee) / rate
    fee_total = b_money*fee
    out_wallet['amount'] =  out_wallet['amount']-b_money
    in_wallet['amount'] = in_wallet['amount']+b_num
    out_wallet.save()
    in_wallet.save()
    trade_type = 0
    save_trade_info(user_info,gateio_info,strategy_info,currency_pair,ticker,trade_type,b_money,fee_total)
    return b_num

def wallet_change_sell(user_info,gateio_info,strategy_info,currency_pair,ticker,in_wallet,out_wallet,filledrate=0):
    rate = float(ticker['last'])#汇率
    b_money = out_wallet['amount']#交易数量
    market_info = Market_info.objects(currency_pair=currency_pair).first()#交易手续费
    fee = float(market_info['fee'])/100
    b_num = (b_money-b_money*fee) * rate
    fee_total = b_money*fee*rate
    out_wallet['amount'] =  out_wallet['amount']-b_money
    in_wallet['amount'] = in_wallet['amount']+b_num
    out_wallet.save()
    in_wallet.save()
    trade_type = 1
    save_trade_info(user_info,gateio_info,strategy_info,currency_pair,ticker,trade_type,b_num,fee_total)
    return b_num

def save_trade_info(user_info,gateio_info,strategy_info,currency_pair,ticker,trade_type,filledAmount,fee_total):
    if trade_type == 0:
        in_cash = currency_pair.split("_")[0]
        out_cash = currency_pair.split("_")[1]
    else:
        in_cash = currency_pair.split("_")[1]
        out_cash = currency_pair.split("_")[0]
    trade_info = Trade_info()
    trade_info.order_number = Trade_info.objects.count()+1
    trade_info.in_cash = in_cash
    trade_info.out_cash = out_cash
    trade_info.rate = float(ticker['last'])
    trade_info.trade_type = trade_type
    trade_info.filledrate = float(ticker['last'])
    trade_info.fee_total = fee_total
    trade_info.filledAmount = filledAmount
    trade_info.leftAmount = 0
    trade_info.user_info=user_info
    trade_info.gateio_info=gateio_info
    trade_info.strategy_info=strategy_info
    trade_info.save()

if __name__ == '__main__':
    last_time = time.time()
    while True:
        logger.info( "-------------------start trade ----------------------------")
        strategy_info_list  = Strategy_info.objects(status__lte=20).all()
        for strategy_info in strategy_info_list:
            if strategy_info['status'] in [1,2,3]:
                currency_pair = strategy_info['currency_pair']
                user_info = strategy_info['user_info']
                gateio_info = strategy_info['gateio_info']
                api_key = gateio_info['api_key']
                secret_key = gateio_info['secret_key']
                name_cn_list = currency_pair.split("_")
                #查看账户情况 创建空钱包
                for name_cn in name_cn_list:
                    wallet = Wallet.objects(name_cn=name_cn,user_info=user_info,gateio_info=gateio_info).first()
                    if wallet == None:
                        wallet = init_wallet(user_info,gateio_info,name_cn,0.0)
                        logger.info( "init {0} {1} wallet success".format(gateio_info['name'],name_cn))
                    else:
                        pass
                    logger.info( "you have ${0} in {1} wallet!".format(wallet['amount'],name_cn))
                
                #判断交易
                gt = GateIO(api_key,secret_key)
                ticker =  gt.ticker(currency_pair)
                rate = float(ticker['last'])#汇率 下单价格
                logger.info( "{0} now price is :{1} ".format(currency_pair,rate))
                if rate<=strategy_info['buy_point'] and strategy_info['status']==1:
                    filledrate = strategy_info['filledrate'] # 交易具体数字
                    in_cash = currency_pair.split("_")[0]
                    out_cash = currency_pair.split("_")[1]
                    rate = float(ticker['last'])#汇率
                    in_wallet = Wallet.objects(name_cn=in_cash,gateio_info=gateio_info,user_info=user_info).first()
                    out_wallet = Wallet.objects(name_cn=out_cash,gateio_info=gateio_info,user_info=user_info).first()
                    if out_wallet['amount'] < filledrate:
                        logger.info( "you have only ${0} {1} in wallet! ".format(out_wallet['amount'],out_cash))
                    else:
                        buyrate = buy(user_info,gateio_info,strategy_info,currency_pair,ticker,in_wallet,out_wallet,filledrate)
                        strategy_info['buyrate']=buyrate
                        strategy_info['status']=2
                        strategy_info.save()
                if rate<=strategy_info['buy_point'] and strategy_info['status']==3 and strategy_info['is_loop']==1:
                    filledrate = strategy_info['filledrate'] # 交易具体数字
                    in_cash = currency_pair.split("_")[0]
                    out_cash = currency_pair.split("_")[1]
                    rate = float(ticker['last'])#汇率
                    in_wallet = Wallet.objects(name_cn=in_cash,gateio_info=gateio_info,user_info=user_info).first()
                    out_wallet = Wallet.objects(name_cn=out_cash,gateio_info=gateio_info,user_info=user_info).first()
                    if out_wallet['amount'] < filledrate:
                        logger.info( "you have only ${0} {1} in wallet! ".format(out_wallet['amount'],out_cash))
                    else:
                        buyrate = buy(user_info,gateio_info,strategy_info,currency_pair,ticker,in_wallet,out_wallet,filledrate)
                        strategy_info['buyrate']=buyrate
                        strategy_info['status']=2
                        strategy_info.save()
                elif rate>=strategy_info['sell_point'] and strategy_info['status']==2:
                    filledrate = strategy_info['filledrate']
                    in_cash = currency_pair.split("_")[1]
                    out_cash = currency_pair.split("_")[0]
                    rate = float(ticker['last'])#汇率
                    in_wallet = Wallet.objects(name_cn=in_cash,gateio_info=gateio_info,user_info=user_info).first()
                    out_wallet = Wallet.objects(name_cn=out_cash,gateio_info=gateio_info,user_info=user_info).first()
                    if out_wallet['amount'] <= 0:
                        logger.info( "you have only ${0} {1} in wallet! ".format(out_wallet['amount'],out_cash))
                    else:
                        sellrate = sell(user_info,gateio_info,strategy_info,currency_pair,ticker,filledrate)
                        strategy_info['sellrate']=buyrate
                        strategy_info['status']=3
                        strategy_info.save()
                else:
                    pass
            else:
                logger.info("----strategyid:【{0}】 is not in status!".format(strategy_info['id']))
        now_time = time.time()
        if now_time-last_time>3600:
            Monitor.heart_beat_send("trade ")
            last_time = now_time
        else:
            pass
        logger.info( "-------------------end trade ----------------------------")
        time.sleep(10)




